from typing import List
from common.enum.strategy_group_enum import StrategyGroup
from common.enum.strategy_type_enum import StrategyType
from dto.strategy_info import StrategyInfoMetadata
from dto.strategy_assessment import RiskAssessment
from dto.strategy_stock_day import StrategyStockDay
from service.strategy.base_strategy import BaseStrategy


class TenDaysDownwardTrendStrategy(BaseStrategy):
    """
    10天内整体下降趋势或峰值出现在5天前，并且当前价格下跌超过10%的策略。
    """

    def analyze(self, trade_info_list: List[StrategyStockDay]) -> RiskAssessment:
        """
        分析10天内是否呈现整体下降趋势，或者峰值出现在5天前且当前价格相比峰值下跌。
        """
        node_point = 0
        description = ""

        # 确保有至少10天的交易数据
        if len(trade_info_list) < 10:
            raise ValueError("数据不足，要求至少10天的交易数据。")

        # 检查是否整体呈下降趋势
        is_downward_trend = all(
            trade_info_list[i].close > trade_info_list[i + 1].close
            for i in range(len(trade_info_list) - 1)
        )

        if is_downward_trend:
            node_point += 5  # 整体下降趋势基础得分5
            description += "过去10天整体呈下降趋势，得5分。\n"

        # 找出峰值和峰值所在天数
        peak_day_index = max(range(len(trade_info_list)), key=lambda i: trade_info_list[i].close)
        peak_price = trade_info_list[peak_day_index].close

        # 检查峰值是否出现在5天前
        if peak_day_index == 5:
            current_price = trade_info_list[0].close  # 当前价格（假设为最近一天的收盘价）
            price_drop_percentage = ((peak_price - current_price) / peak_price) * 100

            if price_drop_percentage > 10:
                node_point += 5  # 下跌超过10%，基础得分5
                additional_points = int(price_drop_percentage // 10) * 5
                node_point += additional_points

                description += (
                    f"峰值出现在5天前（价格 {peak_price}），当前价格 {current_price} 相比峰值下跌了 {price_drop_percentage:.2f}%，"
                    f"额外得 {additional_points} 分。\n"
                )

        return RiskAssessment(
            stock_code=trade_info_list[0].stock_code,
            description=description,
            config=self.strategyConfig(),
            node_point=node_point,
        )

    def strategyConfig(self) -> StrategyInfoMetadata:
        """
        返回策略的配置
        """
        return StrategyInfoMetadata(
            strategy_code="ten_days_downward_trend",
            strategy_name="10天下降趋势或峰值下跌",
            strategy_group=StrategyGroup.RISK,
            strategy_type=StrategyType.PRICE,
            analysis_day=10,
            strategy_level=4,
        )
